package net.cloudsun.tree.orderbinary;

import net.cloudsun.tree.binary.BinaryNode;
import net.cloudsun.tree.binary.BinaryTree;

/**
 * @author Ryan
 * @since
 */
public class OrderBinaryTree<T extends Comparable<T>> extends BinaryTree<T> {

    @Override
    public void delete(T t) {
        innerDelete(t);
    }

    protected OrderBinaryNode<T> innerDelete(T t) {
        // 排序二叉树的删除
        final OrderBinaryNode<T> node = findNode(t);
        return delete(node);
    }

    private OrderBinaryNode<T> delete(OrderBinaryNode<T> node) {
        if (node == null) {
            return null;
        }
        // 如果是root,并且为空
        if (node == root && root.isEmpty()) {
            root = null;
            return node;
        }
        // 如果是叶子
        if (node.isEmpty()) {
            final BinaryNode<T> parent = node.getParent();
            parent.removeChild(node);
            return node;
        }
        // 否则就自己调整了
        node.delete();

        // 对已经删除的进行分析？
        return node;
    }

    @Override
    protected OrderBinaryNode<T> createNode(T t) {
        return new OrderBinaryNode<>(t);
    }

    @Override
    public OrderBinaryNode<T> findNode(T t) {
        return ((OrderBinaryNode<T>) this.root).findNode(t);
    }
}
